#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
快速实例信息查询脚本
提供简洁的实例信息查询功能
"""

import requests
import json
import time
from typing import Dict, List, Any

class QuickQuery:
    """快速查询器"""
    
    def __init__(self, base_url: str = "http://localhost:8080"):
        self.base_url = base_url
    
    def get_servers(self) -> List[Dict[str, Any]]:
        """获取服务器列表"""
        try:
            response = requests.get(f"{self.base_url}/api/v1/servers", timeout=10)
            if response.status_code == 200:
                data = response.json()
                if data.get('success'):
                    return data.get('data', [])
            return []
        except:
            return []
    
    def get_system_status(self) -> Dict[str, Any]:
        """获取系统状态"""
        try:
            response = requests.get(f"{self.base_url}/api/v1/system/status", timeout=10)
            if response.status_code == 200:
                return response.json()
            return {}
        except:
            return {}
    
    def format_status(self, status: str) -> str:
        """格式化状态"""
        status_map = {
            'PENDING': '⏳',
            'RUNNING': '✅',
            'STOPPING': '🛑',
            'STOPPED': '⏸️',
            'TERMINATED': '❌',
            'UNKNOWN': '❓'
        }
        return status_map.get(status, '❓')
    
    def format_region(self, region: str) -> str:
        """格式化地域"""
        region_map = {
            'ap-beijing': '北京',
            'ap-nanjing': '南京',
            'ap-guangzhou': '广州',
            'ap-shanghai': '上海',
            'ap-chongqing': '重庆'
        }
        return region_map.get(region, region)
    
    def format_gpu_type(self, gpu_type: str) -> str:
        """格式化GPU类型"""
        gpu_map = {
            'basic': '基础型',
            'standard': '标准型',
            'performance': '性能型',
            'advanced': '高级型',
            'premium': '高端型'
        }
        return gpu_map.get(gpu_type, gpu_type)
    
    def show_quick_info(self):
        """显示快速信息"""
        print("🔍 当前实例信息")
        print("=" * 50)
        
        # 获取服务器列表
        servers = self.get_servers()
        if not servers:
            print("❌ 无法获取服务器列表")
            return
        
        print(f"📊 总实例数: {len(servers)}")
        
        # 统计各状态数量
        status_count = {}
        region_count = {}
        gpu_count = {}
        
        for server in servers:
            status = server.get('status', 'Unknown')
            region = server.get('region', 'Unknown')
            gpu_type = server.get('gpu_type', 'Unknown')
            
            status_count[status] = status_count.get(status, 0) + 1
            region_count[region] = region_count.get(region, 0) + 1
            gpu_count[gpu_type] = gpu_count.get(gpu_type, 0) + 1
        
        # 显示状态统计
        print("\n📈 状态分布:")
        for status, count in status_count.items():
            status_icon = self.format_status(status)
            print(f"  {status_icon} {status}: {count} 个")
        
        # 显示地域统计
        print("\n🌍 地域分布:")
        for region, count in region_count.items():
            region_name = self.format_region(region)
            print(f"  🏛️ {region_name}: {count} 个")
        
        # 显示GPU类型统计
        print("\n🎮 GPU类型分布:")
        for gpu_type, count in gpu_count.items():
            gpu_name = self.format_gpu_type(gpu_type)
            print(f"  🎮 {gpu_name}: {count} 个")
        
        # 显示实例列表
        print(f"\n📋 实例列表:")
        for i, server in enumerate(servers, 1):
            instance_id = server.get('instance_id', 'Unknown')
            status = server.get('status', 'Unknown')
            region = server.get('region', 'Unknown')
            gpu_type = server.get('gpu_type', 'Unknown')
            
            status_icon = self.format_status(status)
            region_name = self.format_region(region)
            gpu_name = self.format_gpu_type(gpu_type)
            
            print(f"  {i:2d}. {status_icon} {instance_id}")
            print(f"      🌍 {region_name} | 🎮 {gpu_name}")
    
    def show_system_summary(self):
        """显示系统摘要"""
        print("📊 系统摘要")
        print("=" * 50)
        
        status = self.get_system_status()
        if not status or not status.get('success'):
            print("❌ 无法获取系统状态")
            return
        
        data = status['data']
        
        # 系统状态
        system_running = data['system']['running']
        scaling_running = data['scaling']['running']
        
        print(f"🖥️  系统状态: {'✅ 运行中' if system_running else '❌ 已停止'}")
        print(f"🔄 扩缩容状态: {'✅ 运行中' if scaling_running else '❌ 已停止'}")
        
        # 服务器统计
        servers_info = data['servers']['servers']
        print(f"🖥️  总服务器: {servers_info['total']}")
        print(f"✅ 可用服务器: {servers_info['available']}")
        print(f"💚 健康服务器: {servers_info['healthy']}")
        print(f"📊 利用率: {servers_info['utilization_rate']:.1%}")
        
        # 任务统计
        tasks_info = data['servers']['tasks']
        print(f"📋 总任务: {tasks_info['total']}")
        print(f"✅ 已完成: {tasks_info['completed']}")
        print(f"🔄 处理中: {tasks_info['processing']}")
        print(f"⏳ 队列中: {tasks_info['queued']}")
        print(f"❌ 失败数: {tasks_info['failed']}")
        
        # 队列信息
        queue_info = data['queue']
        print(f"📊 队列长度: {queue_info['global_queue_length']}")
        print(f"👥 活跃用户: {queue_info['active_users']}")
        
        # 扩缩容统计
        scaling_info = data['statistics']
        print(f"🔄 扩缩容次数: {scaling_info['total_scaling_actions']}")
        print(f"➕ 创建服务器: {scaling_info['total_servers_created']}")
        print(f"➖ 销毁服务器: {scaling_info['total_servers_destroyed']}")
        print(f"📋 处理任务: {scaling_info['total_tasks_processed']}")
        print(f"✅ 成功任务: {scaling_info['total_tasks_successful']}")
        print(f"❌ 失败任务: {scaling_info['total_tasks_failed']}")

def main():
    import sys
    
    query = QuickQuery()
    
    if len(sys.argv) > 1 and sys.argv[1] == 'summary':
        query.show_system_summary()
    else:
        query.show_quick_info()

if __name__ == '__main__':
    main()
